package com.onlyphoto.onlymall.mvp.view.activity

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.onlyphoto.onlymall.R
import com.onlyphoto.onlymall.api.Urls
import com.onlyphoto.onlymall.base.BaseActivity
import com.bumptech.glide.Glide
import com.onlyphoto.onlymall.bean.WebShareBean
import com.onlyphoto.onlymall.bean.request.CartGoodsBean
import com.onlyphoto.onlymall.bean.response.GoodsDetailsBean
import com.onlyphoto.onlymall.events.ChangeTabEvent
import com.onlyphoto.onlymall.events.PaySuccessEvent
import com.onlyphoto.onlymall.mvp.contract.CGoodsDetails
import com.onlyphoto.onlymall.mvp.presenter.PGoodsDetailsImpl
import com.onlyphoto.onlymall.mvp.view.binder.DetailsHeaderBinder
import com.onlyphoto.onlymall.mvp.view.binder.DetailsImagesBinder
import com.onlyphoto.onlymall.utils.*
import com.onlyphoto.onlymall.widget.AlertDialog
import com.onlyphoto.onlymall.widget.BannerLayout
import com.onlyphoto.onlymall.widget.StylePopupView
import com.onlyphoto.onlymall.widget.StylePopupView.*
import kotlinx.android.synthetic.main.activity_goodsdetails.*
import me.bakumon.statuslayoutmanager.library.DefaultOnStatusChildClickListener
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager
import me.drakeet.multitype.Items
import me.drakeet.multitype.MultiTypeAdapter
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class GoodsDetailsActivity : BaseActivity<PGoodsDetailsImpl>(), CGoodsDetails.IVGoodsDetails, View.OnClickListener {

    var layoutManager: LinearLayoutManager? = null
    var items: Items? = null
    var adapter: MultiTypeAdapter? = null
    var bean: CartGoodsBean? = null
    var goodsBean: GoodsDetailsBean? = null
    private var stylePopupView: StylePopupView? = null

    var reservedOrderId = 0

    override fun retry() {}

    override fun loadData() {
        val id = intent.getIntExtra("goodsId", 0)
        //加载数据
        mPresenter?.getDetails(id)
    }

    override fun init() {
        layoutManager = LinearLayoutManager(this)
        items = Items()
        adapter = MultiTypeAdapter()
        val binder = DetailsHeaderBinder()
        binder.showStyleDialog(object :DetailsHeaderBinder.StyleDialog{
            override fun show() {
                stylePopupView?.setButton(DOUBLE)
                showStyle()
            }
        })
        adapter?.register(GoodsDetailsBean::class.java, binder)
        adapter?.register(String::class.java, DetailsImagesBinder())
        adapter?.items = items!!
        rv_details.layoutManager = layoutManager
        rv_details.adapter = adapter
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun initListener() {
        //点击事件初始化
        back.setOnClickListener(this)
        service.setOnClickListener(this)
        go2cart.setOnClickListener(this)
        add2cart.setOnClickListener(this)
        shop_now.setOnClickListener(this)
        share.setOnClickListener(this)

        rv_details.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val layoutManager = rv_details.layoutManager as LinearLayoutManager
                // 第一个可见Item的位置
                val position = layoutManager.findFirstVisibleItemPosition()
                if (position == 0) {
                    val view = layoutManager.findViewByPosition(position)
                    val scrolledY = -view?.top!!
                    if (scrolledY > 0 && scrolledY <= ConvertUtil.dp2px(this@GoodsDetailsActivity, 100f)) {
                        ll_title.alpha = scrolledY.toFloat() / ConvertUtil.dp2px(this@GoodsDetailsActivity, 100f)
                        back.background.alpha = (1 - scrolledY / ConvertUtil.dp2px(this@GoodsDetailsActivity, 100f)) * 255
                        share.background.alpha = (1 - scrolledY / ConvertUtil.dp2px(this@GoodsDetailsActivity, 100f)) * 255
                    } else if (scrolledY == 0) {
                        ll_title.alpha = 0f
                        back.background.alpha = 255
                        share.background.alpha = 255
                    } else {
                        ll_title.alpha = 1f
                        back.background.alpha = 0
                        share.background.alpha = 0

                    }
                }
            }
        })

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.back -> finish()
            R.id.share -> {
                val wsBean = WebShareBean()
                wsBean.share_url = Urls.URL_SHARE
                wsBean.share_title = goodsBean?.title
                wsBean.share_id = goodsBean?.id.toString()
                wsBean.share_image = goodsBean?.front_img_arr?.get(0)
                wsBean.share_data_type = 2
            }
            R.id.go2cart -> {
                EventBus.getDefault().post(ChangeTabEvent(Constants.PAGE_SHOP_INDEX))
                startActivity(Intent(this, MainActivity::class.java))
            }
            R.id.add2cart -> {
                if (stylePopupView != null) {
                    stylePopupView?.setButton(LEFT)
                    showStyle()
                }
            }
            R.id.shop_now -> {
                if (stylePopupView != null) {
                    stylePopupView?.setButton(RIGHT)
                    showStyle()
                }
            }
            R.id.service -> {
                startActivity(Intent(this, WebViewActivity::class.java)
                        .putExtra("url", Urls.URL_CUSTOM_SERVICE))
            }
        }
    }

    fun showStyle(){
        val window = this.window
        val lp = window.attributes
        lp.alpha = 0.38f
        window.attributes = lp
        stylePopupView?.showAtLocation(cl_details, Gravity.BOTTOM, 0, 0)
    }

    override fun isFullScreen(): Boolean {
        //是否沉浸式， 默认非沉浸式
        return true
    }

    override fun getDetailsSuccess(bean: GoodsDetailsBean) {
        if (bean.allow_cart == 2) {
            add2cart.visibility = View.GONE
        }
        goodsBean = bean
        items?.add(bean)
        items?.addAll(bean.details_img_arr)
        adapter?.notifyDataSetChanged()

        if (stylePopupView == null){
            stylePopupView = StylePopupView(this)
        }
        stylePopupView?.loadData(bean, "", 1)
        stylePopupView?.setFinishedListener {
            mPresenter?.add2Cart(it)
        }
    }

    override fun showEmpty() {
        commonStatusView!!.setContent(R.mipmap.no_details, "暂无商品详情～", "")
        commonStatusView!!.setType(NetWorkStatus.EMPTY)
        showCustomLayout(commonStatusView!!, R.id.ll_content)
    }

    override fun add2CartSuccess() {
        ToastUtil.showToast("添加成功！")
    }

    public override fun initCustomerStatusManager() {
        builder = StatusLayoutManager.Builder(cl_details)
                .setDefaultLoadingText("数据加载中...")
                .setOnStatusChildClickListener(object : DefaultOnStatusChildClickListener() {
                    override fun onCustomerChildClick(view: View) {
                        super.onCustomerChildClick(view)
                        when (view.id) {
                            R.id.ll_content -> {
                                when {
                                    view.tag == NetWorkStatus.FAIL -> retry()
                                    view.tag == NetWorkStatus.ERROR -> retry()
                                    view.tag == NetWorkStatus.EMPTY -> {
                                    }
                                }
                            }
                            else -> retry()
                        }
                    }
                })
                .setDefaultLayoutsBackgroundColor(Color.WHITE)
        statusLayoutManager = builder!!.build()
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: PaySuccessEvent) {
        reservedOrderId = SharePreferenceUtil.getInstance(this).getIntData("reservedOrderId", 0)
        if (reservedOrderId != 0) {
            AlertDialog(this).builder()
                    .setCancelable(false)
                    .setMsg("您购买的定制商品需前往订单详情上传图片")
                    .setPositiveButton("前往") {
                        SharePreferenceUtil.getInstance(this).setIntData("reservedOrderId", 0)
                        startActivity(Intent(this, OrderDetailsActivity::class.java)
                                .putExtra("orderId", reservedOrderId))
                    }.show()
        }
    }

    override fun setContentViewId(): Int {
        return R.layout.activity_goodsdetails
    }

    override fun createPresenter() {
        mPresenter = PGoodsDetailsImpl(mContext, this)
    }

    override fun showLoading() {
        showDefaultDialog()
    }

    override fun hideLoading() {
        hideDefaultDialog()
    }

    class GlideImageLoader : BannerLayout.ImageLoader {

        override fun displayImage(context: Context, path: String, imageView: ImageView) {
            Glide.with(context).load(path).placeholder(R.mipmap.img_default).into(imageView)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
    }
}
